<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title || '内容查看'"
    width="800px"
    :before-close="handleClose"
    class="content-viewer-dialog"
  >
    <div class="content-viewer">
      <!-- 内容类型标识 -->
      <div class="content-header">
        <el-tag :type="getContentTypeTag(type)" size="large">
          {{ getContentTypeLabel(type) }}
        </el-tag>
        <div class="content-actions">
          <el-button size="small" @click="copyContent">
            <el-icon><CopyDocument /></el-icon>
            复制内容
          </el-button>
          <el-button v-if="type === 'url'" size="small" type="primary" @click="openUrl">
            <el-icon><Link /></el-icon>
            打开链接
          </el-button>
        </div>
      </div>
      
      <!-- 内容展示区域 -->
      <div class="content-body">
        <!-- Markdown 内容 -->
        <div v-if="type === 'markdown'" class="markdown-content">
          <div class="content-tabs">
            <el-radio-group v-model="markdownViewMode" size="small">
              <el-radio-button label="preview">预览</el-radio-button>
              <el-radio-button label="source">源码</el-radio-button>
            </el-radio-group>
          </div>
          
          <div v-if="markdownViewMode === 'preview'" class="markdown-preview">
            <div v-html="renderedMarkdown" class="markdown-body"></div>
          </div>
          
          <div v-else class="markdown-source">
            <pre><code>{{ content }}</code></pre>
          </div>
        </div>
        
        <!-- URL 内容 -->
        <div v-else-if="type === 'url'" class="url-content">
          <div class="url-display">
            <el-input
              :model-value="content"
              readonly
              class="url-input"
            >
              <template #prepend>
                <el-icon><Link /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="url-preview">
            <iframe 
              v-if="isValidUrl(content)"
              :src="content" 
              class="url-iframe"
              sandbox="allow-scripts allow-same-origin"
            ></iframe>
            <div v-else class="invalid-url">
              <el-alert
                title="无效的URL"
                type="warning"
                description="提供的URL格式不正确，无法预览"
                show-icon
                :closable="false"
              />
            </div>
          </div>
        </div>
        
        <!-- JSON 内容 -->
        <div v-else-if="type === 'json'" class="json-content">
          <div class="json-viewer">
            <pre><code class="json-code">{{ formatJson(content) }}</code></pre>
          </div>
        </div>
        
        <!-- 普通文本内容 -->
        <div v-else class="text-content">
          <div class="text-display">
            <pre class="text-pre">{{ content }}</pre>
          </div>
        </div>
      </div>
      
      <!-- 内容统计信息 -->
      <div class="content-footer">
        <div class="content-stats">
          <el-text size="small" type="info">
            字符数: {{ content ? content.length : 0 }} | 
            行数: {{ content ? content.split('\n').length : 0 }}
          </el-text>
        </div>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { CopyDocument, Link } from '@element-plus/icons-vue'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  },
  content: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'text' // text, markdown, url, json
  }
})

// Events
const emit = defineEmits(['update:visible'])

// 响应式数据
const markdownViewMode = ref('preview')

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 渲染 Markdown（简单实现，实际项目中建议使用专业的 Markdown 解析库）
const renderedMarkdown = computed(() => {
  if (!props.content) return ''
  
  // 简单的 Markdown 转换（实际项目中应使用 marked 或 markdown-it）
  let html = props.content
    // 标题
    .replace(/^### (.*$)/gim, '<h3>$1</h3>')
    .replace(/^## (.*$)/gim, '<h2>$1</h2>')
    .replace(/^# (.*$)/gim, '<h1>$1</h1>')
    // 粗体
    .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
    // 斜体
    .replace(/\*(.*?)\*/gim, '<em>$1</em>')
    // 代码块
    .replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>')
    // 行内代码
    .replace(/`(.*?)`/gim, '<code>$1</code>')
    // 链接
    .replace(/\[([^\]]+)\]\(([^\)]+)\)/gim, '<a href="$2" target="_blank">$1</a>')
    // 换行
    .replace(/\n/gim, '<br>')
  
  return html
})

// 获取内容类型标签
const getContentTypeTag = (type) => {
  const typeMap = {
    'markdown': 'primary',
    'url': 'warning',
    'json': 'success',
    'text': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取内容类型标签文本
const getContentTypeLabel = (type) => {
  const typeMap = {
    'markdown': 'Markdown 文档',
    'url': '外部链接',
    'json': 'JSON 数据',
    'text': '纯文本'
  }
  return typeMap[type] || '未知类型'
}

// 验证 URL 是否有效
const isValidUrl = (url) => {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

// 格式化 JSON
const formatJson = (jsonString) => {
  try {
    const parsed = JSON.parse(jsonString)
    return JSON.stringify(parsed, null, 2)
  } catch {
    return jsonString
  }
}

// 复制内容
const copyContent = async () => {
  try {
    await navigator.clipboard.writeText(props.content)
    ElMessage.success('内容已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动选择复制')
  }
}

// 打开链接
const openUrl = () => {
  if (isValidUrl(props.content)) {
    window.open(props.content, '_blank')
  } else {
    ElMessage.error('无效的URL地址')
  }
}

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.content-viewer-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.content-viewer {
  display: flex;
  flex-direction: column;
  height: 60vh;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f8f9fa;
}

.content-actions {
  display: flex;
  gap: 10px;
}

.content-body {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content-tabs {
  padding: 10px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafbfc;
}

.markdown-content,
.url-content,
.json-content,
.text-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.markdown-preview,
.markdown-source,
.json-viewer,
.text-display {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.markdown-body {
  line-height: 1.6;
  color: #333;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body h1 {
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 10px;
}

.markdown-body h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 8px;
}

.markdown-body h3 {
  font-size: 1.25em;
}

.markdown-body code {
  background-color: #f6f8fa;
  border-radius: 3px;
  font-size: 85%;
  margin: 0;
  padding: 0.2em 0.4em;
}

.markdown-body pre {
  background-color: #f6f8fa;
  border-radius: 6px;
  font-size: 85%;
  line-height: 1.45;
  overflow: auto;
  padding: 16px;
}

.markdown-body pre code {
  background-color: transparent;
  border: 0;
  display: inline;
  line-height: inherit;
  margin: 0;
  max-width: auto;
  overflow: visible;
  padding: 0;
  word-wrap: normal;
}

.markdown-source pre,
.json-viewer pre,
.text-display pre {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 15px;
  margin: 0;
  overflow-x: auto;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.json-code {
  color: #333;
}

.text-pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.url-display {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.url-input :deep(.el-input-group__prepend) {
  background-color: #f5f7fa;
  color: #909399;
}

.url-preview {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.url-iframe {
  width: 100%;
  height: 400px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.invalid-url {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.content-footer {
  padding: 10px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f8f9fa;
}

.content-stats {
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f8f9fa;
}

/* 滚动条样式 */
.markdown-preview::-webkit-scrollbar,
.markdown-source::-webkit-scrollbar,
.json-viewer::-webkit-scrollbar,
.text-display::-webkit-scrollbar {
  width: 8px;
}

.markdown-preview::-webkit-scrollbar-track,
.markdown-source::-webkit-scrollbar-track,
.json-viewer::-webkit-scrollbar-track,
.text-display::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.markdown-preview::-webkit-scrollbar-thumb,
.markdown-source::-webkit-scrollbar-thumb,
.json-viewer::-webkit-scrollbar-thumb,
.text-display::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.markdown-preview::-webkit-scrollbar-thumb:hover,
.markdown-source::-webkit-scrollbar-thumb:hover,
.json-viewer::-webkit-scrollbar-thumb:hover,
.text-display::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>